﻿Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Web.Configuration

<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://www.openlightgroup.net/PageMappings/07/2009/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class PageMappingsService
    Inherits System.Web.Services.WebService



    Public Sub New()

    End Sub

    Private Function GetFilePath() As String

        Return Server.MapPath(WebConfigurationManager.AppSettings("PageMappingsPath"))

    End Function

    Private Shared Function FormatUrl(ByVal silverlightUrl As String, ByVal mappings As IEnumerable(Of String)) As String

        Dim output As String = String.Empty

        If mappings IsNot Nothing AndAlso Not String.IsNullOrEmpty(mappings.FirstOrDefault) Then

            Dim baseUri = New Uri(silverlightUrl)

            output = String.Format("{0}{1}{2}{3}", _
                                   baseUri.Scheme, _
                                   Uri.SchemeDelimiter, _
                                   baseUri.Authority, _
                                   mappings.FirstOrDefault)

        End If

        Return output

    End Function


    <WebMethod()> _
    Public Function GetHtmlUrl(ByVal silverlightUrl As String) As String

        Dim xdoc = XDocument.Load(GetFilePath())


        Dim mappings = From mapping In xdoc.<PageMappings>.<PageMapping> _
                       Where silverlightUrl.EndsWith(mapping.@silverlightUrl) _
                       Order By mapping.@order Ascending _
                       Select mapping.@htmlUrl

        Return FormatUrl(silverlightUrl, mappings)

    End Function

    <WebMethod()> _
    Public Function GetSilverlightUrl(ByVal htmlUrl As String) As String

        Dim xdoc = XDocument.Load(GetFilePath())

        Dim mappings = From mapping In xdoc.<PageMappings>.<PageMapping> _
                       Where htmlUrl.EndsWith(mapping.@htmlUrl) _
                       Order By mapping.@order Ascending _
                       Select mapping.@silverlightUrl

        Return FormatUrl(htmlUrl, mappings)


    End Function

End Class